/**
 * author:Administrator
 * date:2016 / 2 / 23
 * desc: 订单支付后，生成一个ticket
 * ticket 可以使用，退款
 */
'use strict';

let Repo = require('./TicketRepo.js');
let uuid = require('uuid').v4;
let FormatDate = require('../../../infrastructure/appUtil/FormatDate.js');


let STATUS_ENUM = {
  notUse: 'notUse',         //1,      // 未消费，未过期，未退款的状态
  used: 'used',             //2,      //已消费
  expired: 'expired',       //3,      // 已过期
  refunding: 'refunding',   //4,      // 申请退款
  refunded: 'refunded',     //5       //已退款
};

class Ticket {
  constructor() {
  }

  * store() {
    return yield Repo.store(this);
  }

  /**
   * 从数据库中读取，re-constructor an obj
   * @param pojo
   */
  static rebuild(pojo) {
    let item = new Ticket();
    let keys = Object.keys(pojo);
    for (let key of keys) {
      item[key] = pojo[key];
    }
    return item;
  }

  // 类似工厂方法
  static fromPaidOrder(order) {
    let ticket = new Ticket();
    ticket.orderId = order.id;                        // 生成该订单的order
    ticket.vendorId = order.vendorId;
    ticket.customerId = order.customerId;              // 持有人
    ticket.snapshotId = order.snapshotId;              // 商品快照id
    ticket.refundMoney = order.money;                  // 退款金额

    // 自动生成
    ticket.code = Ticket.genTicketCode();             // 券码,唯一标识
    ticket.createdAt = FormatDate.unixTimestamp();
    ticket.status = STATUS_ENUM.notUse;               // 当前状态

    // 以下id来源与消费时
    //ticket.shopId = pojo.shopId;                      // 实际消费的shop
    //ticket.keeperId = pojo.keeperId;                  // 由keeper录入
    //ticket.consumedAt = pojo.consumedAt;              // 消费发生的时间
    return ticket;
  }

  * consume(keeperId, shopId) {
    if (this.status != STATUS_ENUM.notUse) {
      return false;
    }
    this.shopId = shopId;
    this.keeperId = keeperId;
    this.consumedAt = FormatDate.unixTimestamp();
    this.status = STATUS_ENUM.used;
    yield this.store();
  }

  /**
   * 生成ticket code
   * @returns {*}
   */
  static genTicketCode() {
    return uuid();
  }

}
Ticket.STATUS_ENUM = STATUS_ENUM;
module.exports = Ticket;